package sk.octopuss.archery.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import sk.octopuss.archery.dao.AbstractGenericDao;
import sk.octopuss.archery.dao.ItemDao;
import sk.octopuss.archery.domain.Category;
import sk.octopuss.archery.domain.Item;

@Repository
public class ItemDaoImpl extends AbstractGenericDao<Item> implements ItemDao {

	@Override
	public Item findByCatalogueNumber(final String catalogueNumber) {
		final Query query = em.createQuery("Select i FROM Item i Where i.catalogueNumber ='" + catalogueNumber + "'");
		return (Item) query.getSingleResult();

	}

	@Override
	public List<Item> findAllByName(final String name) {
		final Query query = em.createQuery("Select i FROM Item i Where i.name ='" + name + "'");
		return query.getResultList();
	}

	@Override
	public List<Item> findAll() {
		final Query query = em.createQuery("Select i FROM Item i");
		return query.getResultList();
	}

	@Override
	public Item find(final Long id) {
		final Query query = em.createQuery("Select i FROM Item i Where i.id =" + id);
		return (Item) query.getSingleResult();
	}

	@Override
	public List<Item> findAllEntries(final int firstResult, final int maxResults) {
		return em.createQuery("SELECT i FROM Item i").setFirstResult(firstResult).setMaxResults(maxResults)
				.getResultList();
	}

	@Override
	public List<Category> getParentCategories(final Item item) {
		final List<Category> categories = new ArrayList<Category>();
		Category cat;
		cat = item.getCategory();
		while (cat != null) {
			categories.add(cat);
			cat = cat.getParent();
		}
		return categories;
	}

	@Override
	public long countAll() {
		return (Long) em.createQuery("SELECT COUNT(i) FROM Item i").getSingleResult();
	}

	@Override
	public long save(final Item entity) {
		if (entity.getId() == null) {
			em.persist(entity);
		} else {
			em.merge(entity);
		}
		return entity.getId();
	}

	@Override
	public void delete(final Item entity) {
		em.remove(entity);

	}

}
